import { Entity, Column, ManyToMany, JoinTable, Index, OneToMany } from 'typeorm';
import { BaseEntity } from '@app/common/entities/base.entity';
import { Role } from './role.entity';
import { Conversation } from './conversation.entity';

@Entity('users')
@Index(['username'])
@Index(['email'])
export class User extends BaseEntity {
  @Column({ type: 'varchar', length: 50 })
  username: string;

  @Column({ type: 'varchar', length: 100, nullable: true })
  nickName?: string;

  @Column({ type: 'varchar', length: 100 })
  email: string;

  @Column({ type: 'varchar', length: 255 })
  password: string;

  @Column({ type: 'varchar', length: 20, nullable: true })
  phone?: string;

  @Column({ type: 'varchar', length: 500, nullable: true })
  avatar?: string;

  @Column({ type: 'tinyint', default: 0, comment: '性别: 0=男, 1=女' })
  gender: number;

  @Column({ type: 'tinyint', default: 1, comment: '状态: 0=禁用, 1=启用' })
  status: number;

  @Column({ type: 'varchar', length: 200, nullable: true })
  signature?: string;

  @Column({ type: 'varchar', length: 500, nullable: true })
  address?: string;

  @Column({ type: 'date', nullable: true })
  birthDate?: Date;

  @Column({ type: 'text', nullable: true })
  introduction?: string;

  @Column({
    type: 'enum',
    enum: ['github', 'local', 'google'],
    default: 'local'
  })
  from: 'github' | 'local' | 'google';

  @Column({ type: 'varchar', length: 100, nullable: true })
  uniqueId?: string;

  @Column({ type: 'timestamp', nullable: true })
  lastLoginAt?: Date;

  @Column({ type: 'varchar', length: 45, nullable: true })
  lastLoginIp?: string;

  @Column({ type: 'int', default: 0 })
  loginCount: number;

  @OneToMany(() => Conversation, conversation => conversation.user)
  conversations: Conversation[];

  // 用户角色关联
  @ManyToMany(() => Role, role => role.users, { eager: true })
  @JoinTable({
    name: 'user_roles',
    joinColumn: { name: 'user_id', referencedColumnName: 'id' },
    inverseJoinColumn: { name: 'role_id', referencedColumnName: 'id' }
  })
  roles: Role[];

  // 虚拟属性：获取角色名称数组
  get roleNames(): string[] {
    return this.roles?.map(role => role.name) || [];
  }

  // 虚拟属性：检查是否为管理员
  get isAdmin(): boolean {
    return this.roles?.some(role => role.name === 'admin') || false;
  }

  // 虚拟属性：获取主要角色
  get primaryRole(): string {
    if (!this.roles || this.roles.length === 0) return 'user';
    // 按优先级返回角色：admin > editor > author > user
    if (this.roles.some(role => role.name === 'admin')) return 'admin';
    if (this.roles.some(role => role.name === 'editor')) return 'editor';
    if (this.roles.some(role => role.name === 'author')) return 'author';
    return 'user';
  }
}
